package lc.com.lcpicturebackend.api.deepseek.model;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lc.com.lcpicturebackend.exception.BusinessException;
import lc.com.lcpicturebackend.exception.ErrorCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class DeepSeekApi {

    @Value("${deepseek.api.key}")
    private String apiKey;


    private String systemPrompt="根据用户给出内容进行总结，仅需要给出会话主题,要求不能文字僵硬";

    private static final String API_URL = "https://api.deepseek.com/chat/completions";

    /**
     * 发送消息到DeepSeek API并获取回复
     * @param userMessage 用户消息
     * @return AI回复内容
     */
    public String getChatResponse(String userMessage) {
        // 构造请求体
        JSONObject requestBody = new JSONObject();
        requestBody.set("model", "deepseek-chat");

        // 构造 messages 数组
        JSONObject systemMessage = new JSONObject();
        systemMessage.set("role", "system");
        systemMessage.set("content", systemPrompt);

        JSONObject userMessageObj = new JSONObject();
        userMessageObj.set("role", "user");
        userMessageObj.set("content", userMessage);

        requestBody.set("messages", JSONUtil.createArray().put(systemMessage).put(userMessageObj));
        requestBody.set("stream", false);

        // 发送 POST 请求
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey)
                .body(requestBody.toString())
                .execute();

        // 处理响应
        if (response.isOk()) {
            JSONObject responseBody = JSONUtil.parseObj(response.body());
            return responseBody.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getStr("content");
        } else {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"创建会话失败，请稍后重试");
        }
    }
}